package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.mapper.ShoppingCartMapper;
import com.bwie.pojo.ShoppingCart;
import com.bwie.pojo.User;
import com.bwie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public void addShoppingCart(ShoppingCart shoppingCart) {
        shoppingCartMapper.addShoppingCart(shoppingCart);
        shoppingCartMapper.updateInventory(shoppingCart.getGoodsId());
    }

    @Override
    public List<ShoppingCart> shoppingCartList() {
        return shoppingCartMapper.shoppingCartList();
    }

    @Override
    public void deleteGoods(Integer id) {
        shoppingCartMapper.deleteGoods(id);
    }

    @Override
    public ShoppingCart findCountAndPrice() {
        return shoppingCartMapper.findCountAndPrice();
    }

    @Override
    @Transactional
    public void buyShopping(List<ShoppingCart> shoppingCart) {
        shoppingCartMapper.addOrder(shoppingCart);
        String user = redisTemplate.opsForValue().get("user");
        User user1 = JSONObject.parseObject(user, User.class);
        shoppingCartMapper.clearShopping(shoppingCart);
        shoppingCartMapper.buyShopping(shoppingCart,user1.getId());
        redisTemplate.opsForValue().set("goodsList",JSONObject.toJSONString(shoppingCart));

    }

    @Override
    public User findUserById(Integer id) {
        return shoppingCartMapper.findUserById(id);
    }

    @Override
    public void delAll(List<Integer> ids) {
        shoppingCartMapper.delAll(ids);
    }
}
